package com.edar.dao.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.edar.components.AccountBean;
import com.edar.dao.AccountDao;
import com.edar.dao.util.Page;
import com.edar.dao.util.QueryCondition;
import com.edar.model.Account;
@Repository
public class AccountImpl extends GenericHibernateDao<Account, Long> implements AccountDao{
	/**
	 * HQL主体语句
	 */
	public static final String MAIN_HQL = "From Account as obj";
	/**
	 * HQL中count统计hql片段
	 */
	public static final String COUNT_HQL = "Select Count(obj) ";
	/**
	 * 根据bean组装查询条件
	 */
	public QueryCondition assembly(AccountBean bean) {
		QueryCondition qc = new QueryCondition(MAIN_HQL);
		trans(bean,qc);
		return qc;
	}
	/**
	 * 根据bean组装统计查询条件
	 */
	public QueryCondition assemblyCount(AccountBean bean) {
		QueryCondition qc = new QueryCondition(COUNT_HQL + MAIN_HQL);
		trans(bean,qc);
		return qc;
	}
	/**
	 * 根据bean组装查询条件(名称参数)
	 */
	public QueryCondition assermblyNameQuery(AccountBean bean){
		QueryCondition qc = new QueryCondition(MAIN_HQL);
		transNameQuery(bean, qc);
		return qc;
	}
	
	/**
	 * 根据bean组装统计查询条件(名称参数)
	 */
	public QueryCondition assemblyNameQueryCount(AccountBean bean) {
		QueryCondition qc = new QueryCondition(COUNT_HQL + MAIN_HQL);
		transNameQuery(bean,qc);
		return qc;
	}
	/**
	 * 获取Account总记录数
	 */
	public int count(AccountBean bean){
		return ((Long)iterator(assemblyNameQueryCount(bean)).next()).intValue();
	}
	
	private void trans(AccountBean bean,QueryCondition qc){
		if(bean!=null){
			if(StringUtils.isNotBlank(bean.getName())){
				qc.add("And obj.name like ? ", bean.getName()+"%");
			}
			if(StringUtils.isNotBlank(bean.getEmail())){
				qc.add("And obj.email like ? ", bean.getEmail()+"%");
			}
			if(StringUtils.isNotBlank(bean.getMobile())){
				qc.add("And obj.mobile like ? ", "%"+bean.getMobile()+"%");
			}
		}
	}

	private void transNameQuery(AccountBean bean,QueryCondition qc){
		if(bean!=null){
			if(StringUtils.isNotBlank(bean.getName())){
				qc.add("And obj.name like :name ","name",  bean.getName()+"%");
			}
			if(StringUtils.isNotBlank(bean.getEmail())){
				qc.add("And obj.email like :email ","email", bean.getEmail()+"%");
			}
			if(StringUtils.isNotBlank(bean.getMobile())){
				qc.add("And obj.mobile like :mobile ","mobile", "%"+bean.getMobile()+"%");
			}
		}
	}
	
	public List<?> findByPage(Page<AccountBean> page, AccountBean account) {
		QueryCondition qc = assermblyNameQuery(account);
		qc.setMaxResults(page.getPageSize());
		qc.setOffset(page.getOffset());
		return find(qc);
	}


}
